from django.shortcuts import render 
from home.models import User
from . import models
from django.http import HttpResponseRedirect, HttpResponse
from django.core.paginator import Paginator # 分页功能

def check_login(fnc):
    """装饰器,验证用户是否登录"""
    def wrap(request, *args, **kwargs):
        # 判断cookie的session中信息, 如果没有信息则相当于没有登录,跳转到登录页
        if not hasattr(request, 'session'):
            return HttpResponseRedirect('/log')
        # 判断session中有没有这个键,没有则返回登录
        elif 'user' not in request.session:
            return HttpResponseRedirect('/log')
        return fnc(request, *args, **kwargs)
    return wrap

def yan_info(res):
    """验证用户是否登录, 装饰器要比这个重构函数好"""
    # # 判断cookie的session中信息, 如果没有信息则相当于没有登录,跳转到登录页
    # if not hasattr(res, 'session'):
    #     return False
    # # 判断session中有没有这个键,没有则返回登录
    # elif 'user' not in res.session:
    #     return False
    # return True
    
    
    # 获取登录的ID, 这个id是从User里面找的id
    user_id = res.session['user']['id']
    # 根据已登录的id,找到当前登录的用户
    return User.objects.get(id=user_id)


# Create your views here.
@check_login
def note_view(res):
    """笔记本列表"""
    if res.method == 'GET':
        auser = yan_info(res)
        # 获取用户全部信息
        notes = auser.note_set.all()
        
        # print(notes)
        return render(res, 'note/note.html', locals())
    return HttpResponse("芽儿了嘿!")

@check_login
def note2_view(res):
    """笔记本列表2, 实现分页功能"""
    if res.method == 'GET':
        auser = yan_info(res)
        # 获取用户全部信息
        notes = auser.note_set.all()
        
        # 在此处添加分页功能
        pagin = Paginator(notes, 5) # 参数1是用户的全部信息, 参数2是一页显示多少条数据
        # 获取浏览器当前的页码数, 通过html的 ?page=* 拿到
        cur_page = res.GET.get('page', 1) # 参数2是缺省(默认)值
        # print(type(cur_page), cur_page)
        # 根据浏览器传过来的页码, 拿到指定的一页的数据
        page = Paginator.page(pagin, cur_page)
        # print(notes)
        return render(res, 'note/note_copy.html', locals())
    return HttpResponse("芽儿了嘿!")
    
@check_login
def del_view(res, num_id):
    """删除"""
    ausers = yan_info(res)
    anotes = models.Note.objects.get(user=ausers, id=num_id)
    
    if res.method == 'GET':
        anotes.delete() # 删除根据id的那条数据
        return HttpResponseRedirect('/note')
    return HttpResponse("芽儿了嘿!")

@check_login
def mod_view(res, num_id): # 需要在路由处,捕捉形参捕 /(\d+)
    """修改"""
    ausers = yan_info(res)
    
    # 根据查找到的用户,对比用户名和id一致才行
    anotes = models.Note.objects.get(user=ausers, id=num_id)
    # anotes = models.User.objects.all()
            
    if res.method == 'GET':
        return render(res, 'note/mod.html', locals())
    elif res.method == 'POST':
        tiele_s = res.POST.get('titles_html')
        conyents = res.POST.get('content_html')
        

        # 根据当前登录的用户来添加笔记功能, 此语法相当于一对多,添加外键
        # anote = models.Note(user=ausers)
        
        # 由于上面已经拿到用户id,所以不需要再次获取
        # 根据外键匹配的用户来添加笔记
        anotes.titles = tiele_s
        anotes.content = conyents
        
        # 执行操作
        anotes.save()
        return HttpResponseRedirect('/note')
        
    

@check_login
def add_view(res):
    """添加笔记"""
    if res.method == 'GET':
        return render(res, 'note/add.html')
    elif res.method == 'POST':
        tiele_s = res.POST.get('titles_html')
        conyents = res.POST.get('content_html')
        
        try:
            ausers = yan_info(res)
            
            # 根据当前登录的用户来添加笔记功能, 此语法相当于一对多,添加外键
            anote = models.Note(user=ausers)
            # 根据外键匹配的用户来添加笔记
            anote.titles = tiele_s
            anote.content = conyents
            
            # 执行操作
            anote.save()
            
            # auser = models.Note.objects.create(tieles=tiele_s, content=conyents, user=ausers)
            ls = "添加成功!"
            return render(res, 'note/add.html', locals())
        except Exception as e:
            ls = "糟糕添加失败!"
            return render(res, 'note/add.html', locals())
        